// --------------------------------
// 以下为程序注入 footer 部分代码
// --------------------------------

/**
 * 消息回执
 */
if (type === 'response') {
    const callback = tasks[id];
    if (callback) {
        // 执行成功
        if (response.code === 200) {
            let data = response.data ?? response.result;
            // 返回结果只有一个值，且为 value
            console.log('data_____________', data)
            if (data && Object.keys(data).length == 1 && data.hasOwnProperty("value")) {
                data = data.value;
            }
            callback.resolve({
                code: 200,
                data: data,
                message: response.message || '系统错误',
            });
        }
        // 执行失败
        else {
            callback.reject({
                code: response.code || 500,
                message: response.message || '系统错误',
            });
        }

        delete tasks[id];
    }

} else {
    /**
     * 调用命令
     */
    if (typeof eval(cmd?.fn) === 'function') {
        const dm = globalThis.DeviceManager;
        // 每次都调用create
        create && create();
        // start
        if (cmd.fn === 'create') {
            console.log('开始调用create')
            try {
                // create();
                let taskList = []
                taskMap.map((item) => {
                    try {
                        if (eval(item) !== undefined) {
                            taskList.push(item)
                        }
                    } catch (error) {
                    }
                })
                // 回复start
                parentPort.postMessage({
                    ...message,
                    type: 'nodeResponse',
                    result: {
                        code: 200,
                        type: "start",
                        data: taskList
                    },
                });
            } catch (error) {
                console.log('fn_create>', error)
            }
        }

        else if (cmd.fn === 'init') {
            try {
                init && init();
            } catch (error) {
                console.log('fn_init>', error)
            }
        }
        // subscribe
        else if (cmd.fn === 'subscribe') {
            debugger
            console.log('调用subscribe', appInfo.deviceBind)
            // TODO:fn_subscribe> TypeError: Cannot read properties of undefined (reading 'to')
            // TODO:fn_subscribe> TypeError: Cannot read properties of undefined (reading 'to')
            // TODO:fn_subscribe> TypeError: Cannot read properties of undefined (reading 'to')
            try {
                // const device = dm.deviceInstance[appInfo.deviceList.findIndex((device) => device.id === from)];
                let device
                let deviceIndex
                jump:
                for (let index = 0; index < appInfo.deviceBind.length; index++) {
                    const devices = appInfo.deviceBind[index].devices;
                    for (let i = 0; i < devices.length; i++) {
                        if (devices[i].id === from) {
                            device = dm.deviceInstance[index]
                            deviceIndex = i
                            break jump;
                        }
                    }
                }
                if (device) {
                    const result = await subscribe({
                        deviceIndex,
                        device: device.instance,
                        data: params,
                        state: initData
                    });
                    // parentPort.postMessage(result);
                }

            } catch (error) {
                console.log('fn_subscribe>', error)
            }
        }

        // 所有任务
        else if (taskMap.includes(cmd.fn)) {
            try {
                eval(cmd.fn)({
                    data: params,
                    state: initData
                });
            } catch (error) {
                console.log(`fn_task_${cmd.fn}`, error)
            }
        }

        // 用户自定义函数
        else {
            try {
                const result =
                    await eval(cmd.fn)({
                        data: params,
                        state: initData
                    })

                // 回复给服务器
                parentPort.postMessage({
                    ...message,
                    type: 'nodeResponse',
                    result: {
                        code: 200,
                        "type": "cmd",
                        "source": cmd.source,
                        data: result
                    },
                });
            } catch (error) {
                console.log(`fn_cmd_${cmd.fn}`, error)
            }
        }
    }
    else {
        // 用户调用的不是function
        parentPort.postMessage({
            ...message,
            type: 'nodeResponse',
            result: {
                code: 200,
                "type": "cmd",
                "source": cmd.source,
                data: 'function is undefined'
            },
        });
    }
}


parentPort.postMessage('workerEnd')
    // setTimeout(() => { parentPort.postMessage('workerEnd'), 1000000 })
});
// --------------------------------
// 以上为程序注入 footer 部分代码
// --------------------------------
